﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace kpi.MasterManager
{
    public partial class KpiUserMgr : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ListBox_ShowIncUserName();
        }

        protected void ListBox_ShowIncUserName()
        {
            ListBox_IncUserName.DataSource = Membership.GetAllUsers();
            ListBox_IncUserName.DataBind();
            //Membership.GetAllUsers;
        }

        protected void Button_CreateUser_Click(object sender, EventArgs e)
        {
            Label_DebugMsg.Text = "";

            String[] NamesArray = TextBox_UserNames.Text.Split('\n', '\r');
            for (int i = 0; i < NamesArray.Length; i++)
            {
                Label_DebugMsg.Text += NamesArray[i].ToString();
                if (NamesArray[i].ToString() != "")
                {
                    //Label_DebugMsg.Text += NamesArray[i].ToString();
                    
                    //创建的Password无法登录
                    //SQLProcedure_CreateUser(NamesArray[i].ToString());

                    asp_net_membership_CreateUser(NamesArray[i].ToString(),"123456");
                }
            }
            TextBox_UserNames.Text = "";
        }
        protected void Button_DeleteUser_Click(object sender, EventArgs e)
        {
            Label_DebugMsg.Text = "";

            String[] NamesArray = TextBox_UserNames.Text.Split('\n', '\r');
            for (int i = 0; i < NamesArray.Length; i++)
            {
                Label_DebugMsg.Text += NamesArray[i].ToString();
                if (NamesArray[i].ToString() != "")
                {
                    asp_net_membership_DeleteUser(NamesArray[i].ToString());
                }
            }
            TextBox_UserNames.Text = "";
        }

        protected void SQLProcedure_CreateUser(String UserName)
        {
            //aspnet_Users_CreateUser
            SqlConnection sqlConnection = GetSqlConnection(null);
            sqlConnection.Open();

            //aspnet_Users_CreateUser
            //SqlCommand sqlCommand = new SqlCommand("aspnet_Users_CreateUser", sqlConnection);
            //sqlCommand.CommandType = CommandType.StoredProcedure;
            //sqlCommand.Parameters.Add("@ApplicationId", SqlDbType.UniqueIdentifier);
            //sqlCommand.Parameters.Add("@UserName", SqlDbType.NVarChar, 256);
            //sqlCommand.Parameters.Add("@IsUserAnonymous", SqlDbType.Bit);
            //sqlCommand.Parameters.Add("@LastActivityDate", SqlDbType.DateTime);
            //sqlCommand.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier);

            //sqlCommand.Parameters["@ApplicationId"].Value = new System.Guid("A636DB92-E423-4112-8DAB-3E14E952D872");
            //sqlCommand.Parameters["@UserName"].Value = UserName;
            //sqlCommand.Parameters["@IsUserAnonymous"].Value = 0;
            //sqlCommand.Parameters["@LastActivityDate"].Value = DateTime.Now;
            //sqlCommand.Parameters["@UserId"].Value = System.Guid.NewGuid();

            //aspnet_Membership_CreateUser
            SqlCommand sqlCommand = new SqlCommand("aspnet_Membership_CreateUser", sqlConnection);
            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Parameters.Add("@ApplicationName", SqlDbType.NVarChar, 256);
            sqlCommand.Parameters.Add("@UserName", SqlDbType.NVarChar, 256);
            sqlCommand.Parameters.Add("@Password", SqlDbType.NChar, 128);
            sqlCommand.Parameters.Add("@PasswordSalt", SqlDbType.NChar, 128);
            sqlCommand.Parameters.Add("@Email", SqlDbType.NChar, 256);
            sqlCommand.Parameters.Add("@PasswordQuestion", SqlDbType.NChar, 256);
            sqlCommand.Parameters.Add("@PasswordAnswer", SqlDbType.NChar, 128);
            sqlCommand.Parameters.Add("@IsApproved", SqlDbType.Bit);
            sqlCommand.Parameters.Add("@CurrentTimeUtc", SqlDbType.DateTime);
            sqlCommand.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier);
            //sqlCommand.Parameters.Add("@Email", SqlDbType.NChar, 256);
            //sqlCommand.Parameters.Add("@Email", SqlDbType.NChar, 256);
            //sqlCommand.Parameters.Add("@Email", SqlDbType.NChar, 256);

            sqlCommand.Parameters["@ApplicationName"].Value = "/";
            sqlCommand.Parameters["@UserName"].Value = UserName;
            sqlCommand.Parameters["@Password"].Value = "pGI2P/m9mFogba7oLyoUKvbKZOo=";
            sqlCommand.Parameters["@PasswordSalt"].Value = "mOEiFNSjy1fLnF/PEhFjvg==";
            sqlCommand.Parameters["@Email"].Value = "u2@haoshoucheng.com";
            sqlCommand.Parameters["@PasswordQuestion"].Value = "?";
            sqlCommand.Parameters["@PasswordAnswer"].Value = "!";
            sqlCommand.Parameters["@IsApproved"].Value = 0;
            sqlCommand.Parameters["@CurrentTimeUtc"].Value = DateTime.Now;
            sqlCommand.Parameters["@UserId"].Value = System.Guid.NewGuid();

            sqlCommand.ExecuteNonQuery();

            sqlConnection.Close();
        }

        protected void asp_net_membership_CreateUser(String UserName, String Password)
        {
            //参考资料
            //http://msdn.microsoft.com/zh-cn/library/d8t4h2es(v=vs.110).aspx

            try
            {
                MembershipUser newUser = Membership.CreateUser(UserName, Password);
            }
            catch (MembershipCreateUserException e)
            {
                Label_DebugMsg.Text = GetErrorMessage(e.StatusCode);
            }
            catch (HttpException e)
            {
                Label_DebugMsg.Text = e.Message;
            }
        }

        protected void asp_net_membership_DeleteUser(String UserName)
        {
            try
            {
                Membership.DeleteUser(UserName, true);
            }
            catch(MembershipCreateUserException e)
            {
                Label_DebugMsg.Text = e.Message;
            }
        }

        protected string GetErrorMessage(MembershipCreateStatus status)
        {
            switch (status)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "用户名已经存在。请尝试其他用户名。";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

        protected SqlConnection GetSqlConnection(String SqlConnectionString)
        {
            if (SqlConnectionString == null)
            {
                SqlConnectionString = "Data Source=192.168.0.241;Initial Catalog=kpi_aspnet_db;Persist Security Info=True;User ID=sa;Password=My.SA";
            }
            SqlConnection SqlConnection = new SqlConnection(SqlConnectionString);

            return SqlConnection;
        }       
    }
}